<!--
 * @Author: 徐伟杰
 * @Date: 2022-10-31 11:20:31
 * @LastEditors: 黄宇/Hyuishine
 * @LastEditTime: 2024-05-23 14:09:43
 * @Description: 
 * @Email: 1529315455@qq.com
 * @Company: 3xData
 * @youWant: add you want
-->
<template>
  <view class="offline">
    <action-bar :options="navOptions"></action-bar>
    <view class="offline-box">
      <view v-if="list.length > 0">
        <view class="cu-item case" v-for="(dist, index) in list" :key="index">
          <view class="flex flex-direction">
            <view class="flex justify-between align-center">
              <span>{{ dist.startTime }}</span>
              <view class="flex align-center">
                <span class="text-red margin-right-sm" v-if="dist.checkBtn">重复</span>
                <checkbox-group @change="changeCheck(dist, index)">
                  <checkbox value="cb" color="#FFCC33" style="transform:scale(0.7)" :checked="dist.checkArray" />
                </checkbox-group>
              </view>
            </view>

            <view class="content" style="margin-top: 10rpx">
              <span class="text-blue">执业任务名称:</span>
              <span class="text-red">{{ dist.name }}</span>
            </view>

            <view class="content" style="margin-top: 10rpx">
              <span class="text-blue">执业项目:</span>
              <span>{{ dist.contentName }}</span>
            </view>

            <view class="flex" style="margin-top: 10rpx">
              <span class="text-blue">执业内容:</span>
              <view class="content" style="display: flex; flex-direction: column;">
                <br style="height: 35rpx" />
                <span>是否涉及: {{ dist.involve == '0' ? '不涉及' : '涉及' }}</span>
                <span v-if="dist.involve == '1'">检查数量: {{ dist.checkNum }}</span>
                <span v-if="dist.involve == '1'">检查位置: {{ dist.location }}</span>
                <span>检查情况: {{ dist.content }}</span>
                <span v-if="dist.involve == '1'">发现问题及处理措施: {{ dist.problemAction }}</span>
                <span v-if="dist.involve == '1'">是否合格: {{ dist.judgment == '0' ? '是' : '否' }}</span>
                <div v-if="dist.involve == '1'" style="display: flex; flex-direction: column;">
                  <div v-for="(item, index) in resetUrl(dist.fileUrls)" :key="index"
                    @click="ViewImage(dist.fileUrls, index)">
                    <img class="offline-image" :src="item" alt="">
                  </div>
                </div>
              </view>
            </view>
          </view>
        </view>
        <view style="height: 100rpx"></view>
      </view>
      <no-data v-else text="暂无离线待办数据"></no-data>
    </view>
    <view v-if="list.length > 0">
      <view class="online_box flex justify-around" v-show="Judge()">
        <button class="btn_box btn_delete" @click="remove_btn">全部删除</button>
        <button class="btn_box btn_upload" @click="upload">全部上传</button>
      </view>
      <view class="online_box flex justify-around" v-show="JudgeBtn()">
        <button class="btn_box btn_delete" @click="remove_btn">删除选中</button>
        <button class="btn_box btn_upload" @click="upload_part">选中提交</button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  baseApiUrl
} from '@/config.js';
let _ = require('lodash')
import { mapState } from 'vuex'
let networkTypes = true;
export default {
  computed: {
    ...mapState({
      online_list: state => state.manage.online_list,
    })
  },
  data() {
    return {
      // 页面导航栏的固定写法
      navOptions: {
        statusBar: "dark",
        left: {
          icon: "back",
        },
        center: {
          title: "离线上传",
        },
      },
      list: [], // 从缓存拿离线上传数据(展示出来)
      taskId: null, // 任务id
      baseApiUrl: baseApiUrl,
      checkItem: [], // 勾选中的数据
      checkIndex: [], // 勾选中的数据下标

      cachingList: [], // 缓存到深克隆后的数据
      loading: false,
    }
  },
  onLoad(e) {
    this.taskId = e.taskId
    this.getUnitForm()
  },
  onShow() {
    networkTypes = navigator.onLine;
    this.setInterval = setInterval(() => {
      networkTypes = navigator.onLine;
    }, 5000);
  },
  onUnload() {
    clearInterval(this.setInterval);
  },
  methods: {
    // 获取执业树
    getUnitForm() {
      // 获取缓存
      let list = this.online_list
      console.log(this.online_list)
      let newList = _.cloneDeep(list)
      this.cachingList = newList
      // 获取源数据列表
      let sourceList = []
      // 获取数据信息
      new Promise((resolve, reject) => {
        this.$store.dispatch("unitForm", this.taskId).then((res) => {
          if (res.code == 200) {
            let oldList = res.data.wbDetailList
            try {
              oldList.forEach(item => {
                item.type.forEach(dist => {
                  dist.data.forEach(k => {
                    sourceList.push(k)
                  })
                })
              })
              resolve(sourceList)
            } catch (e) {
              console.log("错误了");
            }
          }
        })
      }).then(item => {
        item.forEach(k => {
          newList.forEach(i => {
            if (k.executeId == i.executeId) {
              let data = {
                checkBtn: k.state == '1' ? true : false,
              }
              Object.assign(i, data)
            }
          })
        })
        this.$nextTick(() => {
          this.list = newList
        })
      })
    },

    resetUrl(urlList) {
      let newList = []
      if (!urlList) return
      let oldList = urlList.split(',')
      oldList.map(item => {
        if (item.indexOf('blob:http://localhost:8080/') != '-1') {
          newList.push(item)
        } else if (item.indexOf('https://www.jxxfxt119.cn:8082/quick') != '-1' || item.indexOf('http://192.168.31.97:8089/xfjsfw/profile/upload') != '-1') {
          newList.push(item)
        } else {
          let dist = this.baseApiUrl + item
          newList.push(dist)
        }
      })
      return newList
    },
    ViewImage(url, index) {
      let newList = []
      let oldList = url.split(',')
      oldList.map(item => {
        if (item.indexOf('blob:http://localhost:8080/') != '-1') {
          newList.push(item)
        } else if (item.indexOf('https://www.jxxfxt119.cn:8082/quick') != '-1' || item.indexOf('http://192.168.31.97:8089/xfjsfw/profile/upload') != '-1') {
          newList.push(item)
        } else {
          let dist = this.baseApiUrl + item
          newList.push(dist)
        }
      })
      uni.previewImage({
        urls: newList,
        current: index
      });
    },
    upload() {
      let that = this
      let list = this.cachingList
      uni.showLoading({
        title: '上传中',
        mask: true
      });
      //   将列表中的图片转化为线上链接
      list.forEach((item, index) => {
        let newFileUrl = [];
        new Promise((resolve, reject) => {
          let imageUrl = item.fileUrls ? item.fileUrls.split(',') : []
          if (imageUrl.length != 0) {
            imageUrl.forEach(dist => {
              if (dist.indexOf('blob:http://localhost:8080/') != '-1') {
                uni.uploadFile({
                  url: that.baseApiUrl + '/common/uploadStaffFile',
                  name: 'file',
                  header: {
                    Authorization: that.$store.state.login.userInfo.token,
                  },
                  filePath: dist,
                  success: uploadFileRes => {
                    let image = that.baseApiUrl + JSON.parse(uploadFileRes.data).fileName
                    newFileUrl.push(image)
                    if (newFileUrl.length == imageUrl.length) {
                      resolve(newFileUrl)
                    }
                  },
                  fail: err => {
                    uni.showToast({
                      title: err,
                      icon: 'none',
                      duration: 2000
                    });
                  }
                });
              } else {
                newFileUrl.push(item)
                if (newFileUrl.length == imageUrl.length) {
                  resolve(newFileUrl)
                }
              }
            })
          } else {
            resolve()
          }
        }).then(dist => {
          let fileUrl = dist ? dist.join(',') : ''
          let monent = {
            checkNum: item.checkNum || null,
            content: item.content || null,
            contentName: item.contentName || null, // 子项任务名称
            executeId: item.executeId || null,
            fileUrls: fileUrl || null, // 上传文件列表
            involve: item.involve || null, // 是否涉及
            location: item.location || null,
            judgment: item.judgment || '',
            maintainDetailId: item.maintainDetailId || null, // 必传项
            problemAction: item.problemAction || null,
            required: item.required || null,
            startTime: item.startTime ? item.startTime : timeStr,
            state: '1',
            taskId: item.taskId || null, // 必传项
          }
          that.$store.dispatch('staffUpdate', monent).then(res => {
            if (res && res.code == 200) {
              list.splice(0, 1)
              if (list.length == 0) {
                that.$store.commit('save_online_list', list)
                uni.hideLoading();
                setTimeout(() => {
                  uni.showToast({
                    title: '上传成功',
                    icon: 'none',
                    duration: 1200
                  })
                }, 1000);
              }
            }
          })
        })
      })
    },
    upload_part() {
      let that = this
      let list = this.cachingList
      let selectList = list.filter(i => {
        return i.checkArray
      })
      let resolve = false
      for (let k = 0; k < selectList.length; k++) {
        if (selectList[k].checkBtn) {
          resolve = true
          break
        }
      }
      that.checkIndex = that.checkIndex.sort((a, b) => a - b)
      if (resolve) {
        uni.showModal({
          title: '提示',
          content: '选中的数据中，已有他人执业的数据，确定提交吗？提交后将覆盖原数据',
          success: function (res) {
            if (res.confirm) {
              selectList.forEach((item, index) => {
                let newFileUrl = [];
                new Promise((resolve, reject) => {
                  let imageUrl = item.fileUrls ? item.fileUrls.split(',') : []
                  if (imageUrl.length != 0) {
                    imageUrl.forEach(dist => {
                      if (dist.indexOf('http://tmp/') != '-1' || dist.indexOf('http://store/') != '-1' || dist.indexOf('wxfile://') != '-1') {
                        uni.uploadFile({
                          url: that.baseApiUrl + '/common/uploadStaffFile',
                          name: 'file',
                          header: {
                            Authorization: that.$store.state.login.userInfo.token,
                          },
                          filePath: dist,
                          success: uploadFileRes => {
                            let image = that.baseApiUrl + JSON.parse(uploadFileRes.data).fileName
                            newFileUrl.push(image)
                            if (newFileUrl.length == imageUrl.length) {
                              resolve(newFileUrl)
                            }
                          },
                          fail: err => {
                            uni.showToast({
                              title: err,
                              icon: 'none',
                              duration: 2000
                            });
                          }
                        });
                      } else {
                        newFileUrl.push(dist)
                        if (newFileUrl.length == imageUrl.length) {
                          resolve(newFileUrl)
                        }
                      }
                    })
                  } else {
                    resolve(imageUrl)
                  }
                }).then(img => {
                  let fileUrl = img ? img.join(',') : ''
                  let monent = {
                    checkNum: item.checkNum || null,
                    content: item.content || null,
                    contentName: item.contentName || null, // 子项任务名称
                    executeId: item.executeId || null,
                    fileUrls: fileUrl || null, // 上传文件列表
                    involve: item.involve || null, // 是否涉及
                    judgment: item.judgment || '',
                    maintainDetailId: item.maintainDetailId || null, // 必传项
                    problemAction: item.problemAction || null,
                    required: item.required || null,
                    startTime: item.startTime ? item.startTime : timeStr,
                    state: '1',
                    taskId: item.taskId || null, // 必传项
                  }
                  that.$store.dispatch('staffUpdate', monent).then(res => {
                    if (res && res.code == 200) {
                      selectList.splice(0, 1)
                      if (selectList.length == 0) {
                        let newList = list.filter((x, y) => !that.checkIndex.some(k => k == y))
                        that.$nextTick(() => {
                          that.$store.commit('save_online_list', newList)
                          that.checkIndex = []
                          that.checkItem = []
                          that.getUnitForm()
                          uni.showToast({
                            title: '保存成功',
                            icon: 'none',
                            duration: 1200
                          })
                        })
                      }
                    }
                  })
                })
              })
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      } else {
        selectList.forEach((item, index) => {
          let newFileUrl = [];
          new Promise((resolve, reject) => {
            let imageUrl = item.fileUrls ? item.fileUrls.split(',') : []
            if (imageUrl.length != 0) {
              imageUrl.forEach(dist => {
                if (dist.indexOf('http://tmp/') != '-1' || dist.indexOf('http://store/') != '-1' || dist.indexOf('wxfile://') != '-1') {
                  uni.uploadFile({
                    url: that.baseApiUrl + '/common/uploadStaffFile',
                    name: 'file',
                    header: {
                      Authorization: that.$store.state.login.userInfo.token,
                    },
                    filePath: dist,
                    success: uploadFileRes => {
                      let image = that.baseApiUrl + JSON.parse(uploadFileRes.data).fileName
                      newFileUrl.push(image)
                      if (newFileUrl.length == imageUrl.length) {
                        resolve(newFileUrl)
                      }
                    },
                    fail: err => {
                      uni.showToast({
                        title: err,
                        icon: 'none',
                        duration: 2000
                      });
                    }
                  });
                } else {
                  newFileUrl.push(dist)
                  if (newFileUrl.length == imageUrl.length) {
                    resolve(newFileUrl)
                  }
                }
              })
            } else {
              resolve(imageUrl)
            }
          }).then(img => {
            let fileUrl = img ? img.join(',') : ''
            let monent = {
              checkNum: item.checkNum || null,
              content: item.content || null,
              contentName: item.contentName || null, // 子项任务名称
              executeId: item.executeId || null,
              fileUrls: fileUrl || null, // 上传文件列表
              involve: item.involve || null, // 是否涉及
              judgment: item.judgment || '',
              maintainDetailId: item.maintainDetailId || null, // 必传项
              problemAction: item.problemAction || null,
              required: item.required || null,
              startTime: item.startTime ? item.startTime : timeStr,
              state: '1',
              taskId: item.taskId || null, // 必传项
            }
            that.$store.dispatch('staffUpdate', monent).then(res => {
              if (res && res.code == 200) {
                selectList.splice(0, 1)
                if (selectList.length == 0) {
                  let newList = list.filter((x, y) => !that.checkIndex.some(k => k == y))
                  that.$nextTick(() => {
                    that.$store.commit('save_online_list', newList)
                    that.checkIndex = []
                    that.checkItem = []
                    that.getUnitForm()
                    uni.showToast({
                      title: '保存成功',
                      icon: 'none',
                      duration: 1200
                    })
                  })
                }
              }
            })
          })
        })
      }
    },
    remove_btn() {
      let that = this
      uni.showModal({
        title: '提示',
        content: '是否确定将选中的数据删除？删除后将丢失这些数据！',
        success: function (res) {
          if (res.confirm) {
            let list = that.online_list
            let newList = that.checkItem;
            let arrList = list.filter((item) => {
              return newList.every((item2) => {
                return item.executeId != item2.executeId;
              });
            });
            that.$store.commit('save_online_list', arrList)
            that.checkIndex = []
            that.checkItem = []
            that.getUnitForm()
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    // 勾选中的数据以及下标，暂存起来
    changeCheck(list, indexs) {
      if (!list.checkArray) list.checkArray = true
      else list.checkArray = false
      if (list.checkArray) {
        this.checkItem.push(list)
        this.checkIndex.push(indexs)
      } else {
        this.checkItem.forEach((item, index) => {
          if (item.executeId == list.executeId) {
            this.checkItem.splice(index, 1)
            this.checkIndex.splice(index, 1)
          }
        })
      }
    },
    // 判断按钮的展示与隐藏
    Judge() {
      let list = this.cachingList
      if (this.checkItem.length == list.length) return true
      else false
    },
    JudgeBtn() {
      let list = this.cachingList
      if (this.checkItem.length != list.length && this.checkItem.length != 0) return true
      else false
    },
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.offline {
  width: 100%;
  min-height: 100vh;

  &-box {
    height: calc(100% - 80rpx);
    background: $OVERALL_SITUATION_BACKGROUND_GRADIENT;
  }
}

.case {
  width: calc(100% - 40rpx);
  margin: 0 auto 24rpx;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 20rpx;
}

.offline-image {
  width: 145rpx;
  height: 145rpx;
}

.online_box {
  width: 100%;
  height: 100rpx;
  background-color: #fff;
  position: fixed;
  bottom: 0;

  .btn_box {
    margin: 10rpx 20rpx;
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    color: #fff;
    border-radius: 20rpx;
    font-size: 28rpx
  }

  .btn_delete {
    background: linear-gradient(90deg, #ff6262 0%, #ff2d2d 100%);
  }

  .btn_upload {
    background: $OVERALL_CONFIRM_BUTTON_COLOR;
  }
}

::v-deep .uni-data-checklist .checklist-group .checklist-box {
  margin-right: 0 !important;
}

::v-deep uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
  color: $OVERALL_SITUATION_BACKGROUND !important
}
</style>